package com.khotyn.heresy.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.Album;
import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.AlbumSelectService;

/**
 * Album select controller
 * 
 * @author khotyn
 * 
 */
@Controller
@RequestMapping("/albumSelect.html")
public class AlbumSelectController {
	@Autowired
	private AlbumSelectService albumSelectService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request) {
		Integer userID = (Integer) session.getAttribute("userID");

		try {
			validate(userID);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		List<Album> albums = albumSelectService.doService(userID);
		return new ModelAndView("albumSelect", "albums", albums);
	}

	private void validate(Integer userID) throws IllegalUrlParamException {
		HeresyErrorMessage errorMessage = null;

		if (userID == null) {
			errorMessage = new HeresyErrorMessage("Please login", "Please login", "login.html");
		}

		if (errorMessage != null) {
			throw new IllegalUrlParamException(errorMessage);
		}
	}
}
